local skel = fk.CreateSkill {
  name = "emo__jiren",
  tags = {Skill.Compulsory},
  dynamic_desc = function (self, player, lang)
    local ret = "emo__jiren_dyn:"
    local mark = player:getTableMark("emo__jiren_removed")
    for i = 1, 6 do
      local choice = "emo__jiren_"..i
      if not table.contains(mark, choice) then
        ret = ret.. "<br>" .. Fk:translate(":" .. choice, lang)
      end
    end
    return ret
  end,
}

Fk:loadTranslationTable{
  ["emo__jiren"] = "己任",
  [":emo__jiren"] = "锁定技，每项限一次，以下时机你执行对应效果，然后扣减一体力上限并从包含关键字的三个技能中获得一个。"..
  "<br>①对一名角色造成伤害后，对其造成一点伤害，获得“军兵战武锋援阵”；"..
  "<br>②击杀一名角色后，摸三张牌，获得“讨伐追袭击诛仇”；"..
  "<br>③装备牌被弃置时，交给一名其他角色，获得“清德守节奋义力”；"..
  "<br>④使用非虚拟四字普通锦囊后，获得此牌，获得“政策决势谏言才”；"..
  "<br>⑤进入濒死状态时，回复一点体力，获得“宠虚抚蛮绝离乱”；"..
  "<br>⑥第六轮开始时，随机使用牌堆一张装备牌，获得“神龙天命心破烈”。",

  [":emo__jiren_dyn"] = "锁定技，每项限一次，以下时机你执行对应效果，然后扣减一体力上限并从包含关键字的三个技能中获得一个。{1}",

  ["#emo__jiren-equip"] = "己任：将你弃置的装备牌交给一名其他角色",
  ["#emo__jiren-skill"] = "己任：选择一个技能获得",
  ["@[:]emo__jiren"] = "己任",

  ["emo__jiren_1"] = "造伤",
  [":emo__jiren_1"] = "①对一名角色造成伤害后，对其造成一点伤害，获得“军兵战武锋援阵”",
  ["emo__jiren_2"] = "击杀",
  [":emo__jiren_2"] = "②击杀一名角色后，摸三张牌，获得“讨伐追袭击诛仇”",
  ["emo__jiren_3"] = "装备",
  [":emo__jiren_3"] = "③装备牌被弃置时，交给一名其他角色，获得“清德守节奋义力”",
  ["emo__jiren_4"] = "锦囊",
  [":emo__jiren_4"] = "④使用非虚拟四字普通锦囊后，获得此牌，获得“政策决势谏言才”",
  ["emo__jiren_5"] = "濒死",
  [":emo__jiren_5"] = "⑤进入濒死状态时，回复一点体力，获得“宠虚抚蛮绝离乱”",
  ["emo__jiren_6"] = "六轮",
  [":emo__jiren_6"] = "⑥第六轮开始时，随机使用牌堆一张装备牌，获得“神龙天命心破烈”",
}

--- 根据关键词获得技能
---@param player ServerPlayer
---@param event TriggerEvent
local doJiren = function (player, event)
  local room = player.room
  if player.dead then return end
  room:changeMaxHp(player, -1)
  if player.dead then return end
  local skillPatterns = {
    [fk.Damage] = "军兵战武锋援阵",[fk.Deathed] = "讨伐追袭击诛仇",[fk.AfterCardsMove] = "清德守节奋义力",
    [fk.CardUseFinished] = "政策决势谏言才",[fk.EnterDying] = "宠虚抚蛮绝离乱",[fk.RoundStart] = "神龙天命心破烈"
  }
  local pattern = skillPatterns[event.class]
  if pattern == nil then return end
  local str = {}
  for i = 1, pattern:len() do
    local s = pattern[i]
    table.insert(str, s)
  end
  local skills = {}
  for _, general_name in pairs(room.general_pile) do
    local general = Fk.generals[general_name]
    for _, skill_name in ipairs(general:getSkillNameList()) do
      local skill = Fk.skills[skill_name]
      if not player:hasSkill(skill, true) and table.find(str, function(s) return string.find(Fk:translate(skill.name), s) end)
      and not skill:hasTag(Skill.AttachedKingdom) then
        table.insert(skills, skill.name)
      end
    end
  end
  if #skills == 0 then return end
  local choice = room:askToChoice(player, { choices = table.random(skills, 3), skill_name = skel.name, detailed = true})
  room:handleAddLoseSkills(player, choice)
end

---@param player ServerPlayer
---@param event TriggerEvent
local addRecord = function (player, event)
  local event_list = {fk.Damage, fk.Deathed, fk.AfterCardsMove, fk.CardUseFinished, fk.EnterDying, fk.RoundStart}
  local choice = "emo__jiren_"..table.indexOf(event_list, event.class)
  player.room:addTableMark(player, "emo__jiren_removed", choice)
end

---@param player ServerPlayer
---@param event TriggerEvent
local triggerable = function (player, event)
  if not player:hasSkill(skel.name) then return false end
  local event_list = {fk.Damage, fk.Deathed, fk.AfterCardsMove, fk.CardUseFinished, fk.EnterDying, fk.RoundStart}
  local index = table.indexOf(event_list, event.class)
  if index < 1 then return false end
  local choice = "emo__jiren_"..index
  return not table.contains(player:getTableMark("emo__jiren_removed"), choice)
end

skel:addEffect(fk.Damage, {
  anim_type = "offensive",
  can_trigger = function (self, event, target, player, data)
    if not triggerable(player, event) then return false end
    return player == target and not data.to.dead
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    addRecord (player, event)
    room:damage { from = player, to = data.to, damage = 1, skillName = skel.name }
    doJiren (player, event)
  end,
})

skel:addEffect(fk.Deathed, {
  anim_type = "drawcard",
  can_trigger = function (self, event, target, player, data)
    if not triggerable(player, event) then return false end
    return data.killer == player
  end,
  on_use = function (self, event, target, player, data)
    addRecord (player, event)
    player:drawCards(3, skel.name)
    doJiren (player, event)
  end,
})

skel:addEffect(fk.AfterCardsMove, {
  anim_type = "support",
  can_trigger = function (self, event, target, player, data)
    if not triggerable(player, event) then return false end
    local room = player.room
    if #room:getOtherPlayers(player, false) == 0 then return false end
    local ids = {}
    for _, move in ipairs(data) do
      if move.from == player and move.moveReason == fk.ReasonDiscard then
        for _, info in ipairs(move.moveInfo) do
          if Fk:getCardById(info.cardId).type == Card.TypeEquip and room:getCardArea(info.cardId) == Card.DiscardPile then
            table.insert(ids, info.cardId)
          end
        end
      end
    end
    if #ids > 0 then
      event:setCostData(self, ids)
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    addRecord (player, event)
    local tos = room:askToChoosePlayers(player, {
      targets = room:getOtherPlayers(player), min_num = 1, max_num = 1, skill_name = skel.name,
      cancelable = false, prompt = "#emo__jiren-equip"
    })
    if #tos > 0 then
      room:moveCardTo(event:getCostData(self), Card.PlayerHand, tos[1], fk.ReasonGive, skel.name, nil, true, player)
    end
    doJiren (player, event)
  end,
})

skel:addEffect(fk.CardUseFinished, {
  anim_type = "drawcard",
  can_trigger = function (self, event, target, player, data)
    if not triggerable(player, event) then return false end
    return player == target and data.card:isCommonTrick() and (not data.card:isVirtual() or #data.card.subcards > 0)
      and Fk:translate(data.card.trueName, "zh_CN"):len() == 4 and player.room:getCardArea(data.card) == Card.Processing
  end,
  on_cost = function (self, event, target, player, data)
    addRecord (player, event)
    player.room:obtainCard(player, data.card, true, fk.ReasonPrey, player, skel.name)
    doJiren (player, event)
  end,
})

skel:addEffect(fk.EnterDying, {
  anim_type = "defensive",
  can_trigger = function (self, event, target, player, data)
    if not triggerable(player, event) then return false end
    return player == target
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    addRecord (player, event)
    room:recover { num = 1, skillName = skel.name, who = player , recoverBy = player }
    doJiren (player, event)
  end,
})

skel:addEffect(fk.RoundStart, {
  anim_type = "drawcard",
  can_trigger = function (self, event, target, player, data)
    if not triggerable(player, event) then return false end
    return player.room:getBanner("RoundCount") == 6
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    addRecord (player, event)
    for _, cid in ipairs(room.draw_pile) do
      local card = Fk:getCardById(cid)
      if card.type == Card.TypeEquip and player:canUseTo(card, player) then
        room:useCard({ from = player, tos = {player}, card = card })
        break
      end
    end
    doJiren (player, event)
  end,
})

return skel
